package com.aruba.mvvmapplication.remote

import android.util.Log
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import com.aruba.mvvmapplication.database.AppDatabase
import com.aruba.mvvmapplication.entity.MovieEntity
import com.aruba.mvvmapplication.extension.isConnectedNetwork
import com.aruba.mvvmapplication.init.AppHelper

/**
 * Created by aruba on 2021/9/24.
 */
@OptIn(ExperimentalPagingApi::class)
class MovieRemoteMediator(
    private val api: MovieService,
    private val appDatabase: AppDatabase
) : RemoteMediator<Int, MovieEntity>() {

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, MovieEntity>
    ): MediatorResult {
        try {
            //1.判断loadType
            val pageKey = when (loadType) {
                //首次加载
                LoadType.REFRESH -> null
                //REFRESH之后还会调用load（REFRESH时数据库中没有数据），来加载开头的数据，直接返回成功就可以了
                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = false)
                //加载更多
                LoadType.APPEND -> {
                    val lastItem = state.lastItemOrNull() ?: return MediatorResult.Success(
                        endOfPaginationReached = true
                    )
                    lastItem.page//返回当前页
                }
            }

            //无网络从本地数据库获取数据
            if (!AppHelper.mContext.isConnectedNetwork()) {
                return MediatorResult.Success(endOfPaginationReached = false)
            }

            //2.请求网络分页数据
            val page = pageKey ?: 0
            val result = api.getMovieList(
                page * state.config.pageSize,
                state.config.pageSize
            )
            
            //服务器对象转换为本地数据库对象
            val entity = result.map {
                MovieEntity(
                    id = it.id,
                    title = it.title,
                    cover = it.cover,
                    rate = it.rate,
                    page = page + 1
                )
            }
            //3.存入数据库
            val movieDao = appDatabase.movieDao()
            appDatabase.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    movieDao.clear()
                }

                movieDao.insert(entity)
            }

            val endOfPaginationReached = result.isEmpty()
            return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
        } catch (e: Exception) {
            return MediatorResult.Error(e)
        }
    }

}